package com.wu.xtkong.myInterceptor;


import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import com.wu.xtkong.customNote.MyRedisCache;
import com.wu.xtkong.domain.User;

/**
 * @author 吴冬冬
 * @version 创建时间：2017年4月28日 下午2:51:59
 * 
 */
@Aspect
@Configuration
@SuppressWarnings("all")
public class MyCacheInterceptor {
	@Autowired
	private RedisTemplate redisTemplate;
	
	@Pointcut("execution(* com.wu.*.service.impl..*(..))")
	private void anyMethod() {
	}// 定义一个切入点

	@Before("anyMethod() && args(name)")
	public void doAccessCheck(String name) {
		System.out.println(name);
		System.out.println("前置通知");
	}

	@AfterReturning("anyMethod()")
	public void doAfter() {
		System.out.println("后置通知");
	}

	@After("anyMethod()")
	public void after() {
		System.out.println("最终通知");
	}

	@AfterThrowing("anyMethod()")
	public void doAfterThrow() {
		System.out.println("例外通知");
	}

	@Around("anyMethod()")
	public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
		//获取当前节点实现方法对象
		Signature sig = pjp.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = pjp.getTarget();
        Method m = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        //判断是否含有MyRedisCache注解
        boolean isExistMethod = m.isAnnotationPresent(MyRedisCache.class);
        Object object = null;
        String key = null;
        if(isExistMethod){//如果含有该注解
        	//获取方法返回对象
        	Class returnType = msig.getReturnType(); 
        	System.out.println(returnType.getName());
        	
        	//获取注解对象
			MyRedisCache mrc = m.getAnnotation(MyRedisCache.class);
			key = mrc.key();
			System.out.println("注解key="+key);
			//去缓存中取数据
			//User u = new User("小红","女","23");
			object = redisTemplate.opsForValue().get(key);
			if(object != null){
				return object;
			}
		}
        //如果缓存中没有缓存，直接运行方法取值
        object = pjp.proceed();
        redisTemplate.opsForValue().set(key,object);
		return object;
	}
}
